package com.google.code.twiddling.core.history;

import com.google.code.twiddling.core.util.PreferencesUtil;

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
import java.util.prefs.Preferences;

/**
 * @author <a href="mailto:yy.young@gmail.com">Young Yang</a>
 * @create Dec 22, 2008 8:37:28 PM
 */
public class HistoryManager {

    private Preferences historyPreferences = PreferencesUtil.getTwiddlingPreferences().node(HISTORY_KEY);


    private static final HistoryManager instance = new HistoryManager();
    private final static String HISTORY_KEY = "history";
    //TODO: recode command exucute time point
//    private final static String HISTORY_TIME_KEY = "history_time";


    private List<String> historyCommands = new ArrayList<String>();

    private final static String SPLIT_CHARS = ">=<";
    private final static int MAX_COUNT = 1000;

    private HistoryManager() {
        String historyString = historyPreferences.get(HISTORY_KEY, "");
        String[] cmdArray = fromString(historyString);
        historyCommands.addAll(Arrays.asList(cmdArray));
    }

    public static HistoryManager getInstance(){
        return instance;
    }

    public void addCommand(String cmd){
        while(historyCommands.size() >= MAX_COUNT) {
            historyCommands.remove(0);
        }
        historyCommands.add(cmd);
        historyPreferences.put(HISTORY_KEY, toString(historyCommands.toArray(new String[historyCommands.size()])));
        try {
            historyPreferences.flush();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<String> getHistoryCommands(){
        return Collections.unmodifiableList(historyCommands);
    }

    public String getLastCommand(){
        return historyCommands.get(historyCommands.size() - 1);
    }

    private static String[] fromString(String historyString){
        if(historyString == null || historyString.trim().equals("")) {
            return new String[0];
        }
        else {
            return historyString.split(SPLIT_CHARS);
        }
    }

    private static String toString(String[] historyArray){
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<historyArray.length ;i++){
            if(i>0) {
                sb.append(SPLIT_CHARS);
            }
            sb.append(historyArray[i].trim());

        }
        return sb.toString();
    }

}
